package com.rookie.im;

import com.rookie.im.server.ImServer;
import com.rookie.im.server.config.AppConfig;
import com.rookie.im.server.utils.RabbitManager;
import com.rookie.im.server.utils.RedisManager;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.representer.Representer;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

public class Starter {
    public static void main(String[] args) {
        AppConfig config = settings();
        new Thread(() -> {
            new ImServer(config.getRookie()).run();
        }).start();
        RedisManager.init(config.getRookie().getRedis());
        RabbitManager.init(config.getRookie().getRabbitmq());
        RabbitManager.reciver();
    }

    public static AppConfig settings() {
        Representer represent = new Representer();
        represent.getPropertyUtils().setSkipMissingProperties(true);
        Yaml yaml = new Yaml(represent);
        Map<String, Object> yamlData = yaml.load(Starter.class.getClassLoader().getResourceAsStream("application.yaml"));
        Properties properties = loadProperties("application.properties");
        replacePlaceholders(yamlData, properties);
        String subMapYaml = yaml.dump(yamlData);
        return yaml.loadAs(subMapYaml, AppConfig.class);
    }

    private static void replacePlaceholders(Map<String, Object> yamlMap, Properties properties) {
        for (Map.Entry<String, Object> entry : yamlMap.entrySet()) {
            if (entry.getValue() instanceof String) {
                String value = (String) entry.getValue();
                for (String key : properties.stringPropertyNames()) {
                    value = value.replace("${" + key + "}", properties.getProperty(key));
                }
                entry.setValue(value);
            } else if (entry.getValue() instanceof Map) {
                replacePlaceholders((Map<String, Object>) entry.getValue(), properties);
            }
        }
    }
    // 加载properties文件
    private static Properties loadProperties(String path) {
        Properties props = new Properties();
        try {
            InputStream input = Starter.class.getClassLoader().getResourceAsStream(path);
            props.load(input);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return props;
    }
}